package com.enhe.gck.fg;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.enhe.gck.communal.PublicConstant;
import com.enhe.gck.communal.PublicMethod;
import com.enhe.gck.communal.PublicReturn;
import com.enhe.gck.pojo.PouringOrder;
import com.enhe.gck.pojo.SupplyOrder;
import com.enhe.gck.pojo.WeighOther;
import com.kuangkie.carbon.common.IntegrationMsg;
import com.kuangkie.carbon.common.RemoveRecordInfo;
import com.kuangkie.carbon.fg.*;
import com.kuangkie.carbon.fg.ops.ProRecordOpsBuilder;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import com.enhe.gck.CarbonBaseConstant; //模型Code
import com.enhe.gck.CarbonEnumKeyValue; //枚举字典信息
import com.enhe.gck.CarbonRelationType; //关系类型Code
import com.enhe.gck.item.PouringOrderHWANE18490Item; // 模型属性Code

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collection;

@Slf4j
@Repository(value = "hwane18490366042330866425862")
public class PouringOrderHWANE18490BNB implements SecondRoundImproveFuncGroup, FuseCallBackFuncGroup, RemoveFuncGroup , FetchFuncGroup{
	@Resource
	private IcCardHWANE16640BNB icCardHWANE16640BNB;
	@Override
	public void secondImprove(FuncGroupContext context, ProRecord proRecord, FGRecordComplexus recordComplexus,
			ImproveResultFactory improveResultFactory) {
		PouringOrder pouringOrder=proRecord.getBean(PouringOrder.class);
		log.info("添加/修改倒料订单业务开始:{}", JSON.toJSON(pouringOrder));

		if(pouringOrder.getIsCancel() == null || !pouringOrder.getIsCancel()){
			if(String.valueOf(CarbonEnumKeyValue.操作命令_订单_手工补录_ddsgbl).equals(pouringOrder.getCommand())){
				inputHand(proRecord,improveResultFactory,proRecord.isNew()?PublicMethod.getOrderCodePM():pouringOrder.getOrder());
				return;
			}

			if(!validation(pouringOrder,improveResultFactory)){
				return;
			}

			setFinishTime(pouringOrder,improveResultFactory);

			boolean flagIc=true;
			if(!proRecord.isNew()){
				PouringOrder pouringOrderOld=CarbonPanel.getRecordDiscover(CarbonBaseConstant.倒料订单_dldd).getRecordBean(proRecord.getRecordCode(),PouringOrder.class);
				if(pouringOrderOld!=null){
					if(String.valueOf(PublicConstant.OrderStateOver).equals(pouringOrder.getState())&&String.valueOf(PublicConstant.OrderStateOver).equals(pouringOrderOld.getState())){
						flagIc=false;
					}
				}
			}
			if(flagIc){
				if(!ICCar(proRecord,improveResultFactory)){
					return;
				}
			}

			ProRecordOpsBuilder setData=improveResultFactory.getCurrentProRecordOpsBuilder();
			if(proRecord.isNew()){
				//配置公用数据
				setData.putAttribute(PouringOrderHWANE18490Item.基本属性组_单号,PublicMethod.getOrderCodePM());

				OperationLogHWANE21797BNB.save(improveResultFactory,7,1,proRecord.getRecordCode());
			}
		}else {
			if(!proRecord.isNew()){
				if(pouringOrder.getIsCancel()!=null&&pouringOrder.getIsCancel()){
					PouringOrder orderOld=CarbonPanel.getRecordDiscover(CarbonBaseConstant.倒料订单_dldd).getRecordBean(proRecord.getRecordCode(),PouringOrder.class,1);
					if(orderOld!=null){
						if(!(orderOld.getIsCancel()!=null&&orderOld.getIsCancel())){
							OperationLogHWANE21797BNB.save(improveResultFactory,7,3,proRecord.getRecordCode());
						}
					}
				}
			}
		}
	}

	/**
	 * 参数验证
	 */
	public boolean validation(PouringOrder pouringOrder,ImproveResultFactory improveResultFactory) {
		if(StringUtils.isEmpty(pouringOrder.getState())||
//				StringUtils.isEmpty(pouringOrder.getIcCard())||
				StringUtils.isEmpty(pouringOrder.getInputType()) ||
				StringUtils.isEmpty(pouringOrder.getOrderSource())
		){
			PublicMethod.returnMessage(improveResultFactory, PublicReturn.ORDER_10);
			return false;
		}
		return true;
	}
	/**
	 * 设置完成时间
	 */
	private void setFinishTime(PouringOrder order,ImproveResultFactory improveResultFactory){
		ProRecordOpsBuilder setData=improveResultFactory.getCurrentProRecordOpsBuilder();
		log.info("设置完成时间");
		if(order.getFinishTime()==null){
			if(String.valueOf(CarbonEnumKeyValue.订单记录_状态_已出厂_ycc).equals(order.getState())){
				PouringOrder orderOrigin=CarbonPanel.getRecordDiscover(CarbonBaseConstant.倒料订单_dldd).getRecordBean(order.getRecordCode(),PouringOrder.class);
				if(orderOrigin!=null){
					if(!String.valueOf(CarbonEnumKeyValue.订单记录_状态_已出厂_ycc).equals(orderOrigin.getState())){
						log.info("未完成过，设置时间");
						setData.putAttribute(PouringOrderHWANE18490Item.基本属性组_完成时间, LocalDateTime.now());
					}else {
						if(orderOrigin.getFinishTime()==null){
							log.info("完成过，未设置时间");
							setData.putAttribute(PouringOrderHWANE18490Item.基本属性组_完成时间, LocalDateTime.now());
						}
					}
				}
			}
		}
	}

	/**
	 * IC卡逻辑 改为待过一磅
	 */
	private boolean ICCar(ProRecord proRecord,ImproveResultFactory improveResultFactory){
		boolean isOk=true;
		if(StrUtil.isNotBlank(proRecord.getString(PouringOrderHWANE18490Item.基本属性组_IC卡号))){
			isOk =icCardHWANE16640BNB.verifyCardNumber(improveResultFactory,proRecord.getRecordCode(),proRecord.getString(PouringOrderHWANE18490Item.基本属性组_IC卡号));
		}
		return isOk;
	}

	/**
	 * 手工补录
	 */
	public boolean inputHand(ProRecord proRecord,ImproveResultFactory improveResultFactory,String code) {
		log.info("手工补录业务开始:{}",proRecord.toJson());
		ProRecordOpsBuilder setData=improveResultFactory.getCurrentProRecordOpsBuilder();
		PouringOrder order=proRecord.getBean(PouringOrder.class);
		setData.putAttribute(PouringOrderHWANE18490Item.基本属性组_单号,code);
		//修改 先毛后皮
//		setData.putAttribute(PouringOrderHWANE18490Item.基本属性组_重量,PublicMethod.subtractBigDecimal(order.getWeight2(),order.getWeight1()));
		setData.putAttribute(PouringOrderHWANE18490Item.基本属性组_重量,PublicMethod.subtractBigDecimal(order.getWeight1(),order.getWeight2()));
		setData.putAttribute(PouringOrderHWANE18490Item.基本属性组_状态,CarbonEnumKeyValue.订单记录_状态_已出厂_ycc);
		log.info("补录地磅信息开始");
		//修改 先毛后皮
//		PublicMethod.saveWeigh(improveResultFactory,code,BigDecimal.valueOf(order.getWeight1()), BigDecimal.ZERO,BigDecimal.ZERO,1,order.getWeight1Time());
//		PublicMethod.saveWeigh(improveResultFactory,code,BigDecimal.ZERO,BigDecimal.valueOf(order.getWeight2()),BigDecimal.ZERO,2,order.getWeight2Time());

		PublicMethod.saveWeigh(improveResultFactory,code, BigDecimal.ZERO,BigDecimal.valueOf(order.getWeight1()),BigDecimal.ZERO,1,order.getWeight1Time());
		PublicMethod.saveWeigh(improveResultFactory,code,BigDecimal.valueOf(order.getWeight2()),BigDecimal.ZERO,BigDecimal.ZERO,2,order.getWeight2Time());
		log.info("补录地磅信息结束");
		log.info("手工补录业务结束:");
		return true;
	}

	@Override
	public boolean afterFusition(FuncGroupContext funcGroupContext, FuseContext fuseContext, String s) {
		saveNew(s);
		return true;
	}

	@Override
	public boolean beforeRemove(FuncGroupContext funcGroupContext, RemoveRecordInfo removeRecordInfo, DeleteMessageFactory defDeleteMessageFactory) {
		Collection<String> list=removeRecordInfo.getRecordCodes();
		log.info("删除业务开始:{}",list);
		boolean isOk=true;
		if(list!=null){
			for (String x : list) {
				FGRecord info=CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.倒料订单_dldd).getProConJunctionFactory()
						.addEqual(CarbonBaseConstant.COLUMN_ABP0001,x)
						.addEqual(PouringOrderHWANE18490Item.基本属性组_状态,PublicConstant.OrderStateOver)
						.addEqual(PouringOrderHWANE18490Item.基本属性组_是否作废,false)
						.goBack().queryARecord();
				if(info!=null){
					PublicMethod.returnMessage(defDeleteMessageFactory, PublicReturn.DELETE_1);
					isOk=false;
				}
			}
		}
		log.info("删除业务结束");
		return isOk;
	}


	/**
	 * 新增订单
	 * @param s
	 */
	public void saveNew(String s) {
		ProRecord proRecord=CarbonPanel.getRecordDiscover(CarbonBaseConstant.倒料订单_dldd).getProRecord(s);
		log.info("倒料订单新增开始:{}",s);
		if(proRecord==null){
			return;
		}
		PouringOrder order=proRecord.getBean(PouringOrder.class);
		if(order.getIsCancel() == null || !order.getIsCancel()){
			if(order.getEffectiveDeadline()==null||order.getEffectiveDeadline().isAfter(LocalDateTime.now())){
				log.info("倒料订单:{}",proRecord.toJson());
				if(String.valueOf(CarbonEnumKeyValue.订单记录_录入类型_系统下单_xtxd).equals(order.getInputType())){
//					if(String.valueOf(PublicConstant.OrderStateOver).equals(order.getState())&&!StrUtil.isBlank(order.getIcCard())){
					if(String.valueOf(PublicConstant.OrderStateOver).equals(order.getState())){
						PouringOrder info;
						if(StrUtil.isNotBlank(order.getIcCard())){
							info=CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.倒料订单_dldd).getProConJunctionFactory()
									.addEqual(PouringOrderHWANE18490Item.基本属性组_IC卡号,order.getIcCard())
									.addEqual(PouringOrderHWANE18490Item.基本属性组_是否作废,false)
									.addNotEqual(PouringOrderHWANE18490Item.基本属性组_状态,PublicConstant.OrderStateOver)
									.goBack().queryABean(PouringOrder.class);
						}else {
							RecordQueryProConJunctionFactory que=CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.倒料订单_dldd).getProConJunctionFactory()
									.addEqual(PouringOrderHWANE18490Item.基本属性组_是否作废,false)
									.addNotEqual(PouringOrderHWANE18490Item.基本属性组_状态,PublicConstant.OrderStateOver);
							que.getRelationCriterionFactory(CarbonBaseConstant.车辆管理_clgl)
									.setInRelationTypes(CarbonRelationType.RR_倒料订单_车牌号_车辆管理)
									.setInGuestCodes(proRecord.getGuestRecordCode(CarbonRelationType.RR_倒料订单_车牌号_车辆管理));
							info=que.goBack().queryABean(PouringOrder.class);
						}
						if(info==null){
							log.info("倒料订单完成生成新订单:{}",JSON.toJSON(order));
							FGRecordComplexusBuilder fGRecordComplexusBuilder=CarbonPanel.getFGRecordComplexusBuilder();
							fGRecordComplexusBuilder.getProRecordBuilder(CarbonBaseConstant.倒料订单_dldd)
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_IC卡号,order.getIcCard())
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_名称,order.getName())
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_状态,CarbonEnumKeyValue.订单记录_状态_待过一磅_dgyb)
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_录入类型,CarbonEnumKeyValue.订单记录_录入类型_系统下单_xtxd)
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_订单来源,CarbonEnumKeyValue.订单来源_PC_)
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_是否作废,false)
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_类型,order.getType())
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_车皮重,order.getCarWeightTare())
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_备注,order.getRemark())
									.putAttribute(PouringOrderHWANE18490Item.基本属性组_有效截至时间,order.getEffectiveDeadline())
									.addRelation(CarbonRelationType.RR_倒料订单_司机_司机管理,proRecord.getGuestRecordCode(CarbonRelationType.RR_倒料订单_司机_司机管理))
									.addRelation(CarbonRelationType.RR_倒料订单_车牌号_车辆管理,proRecord.getGuestRecordCode(CarbonRelationType.RR_倒料订单_车牌号_车辆管理))
									.addRelation(CarbonRelationType.RR_倒料订单_品种信息_物料管理,proRecord.getGuestRecordCode(CarbonRelationType.RR_倒料订单_品种信息_物料管理))
							;
							IntegrationMsg msg=CarbonPanel.getRecordIntegration(CarbonBaseConstant.倒料订单_dldd).integrate(fGRecordComplexusBuilder.getFGRecordComplexus());
							if(!msg.success()){
								log.info("生成新倒料单失败:{}",msg.getRefuseMsgContentStr());
							}
						}else {
							log.info("存在信息,不生成新订单:{}",JSON.toJSON(info));
						}
					}
				}
			}else {
				log.info("已过有效时间,不生成新订单:{}",order.getEffectiveDeadline());
			}
		}else {
			log.info("已作废,不生成新订单:{}",JSON.toJSON(proRecord));
		}
	}

	@Override
	public void fetchImprove(FuncGroupContext funcGroupContext, FGRecord fgRecord, FetchResultFactory fetchResultFactory) {
		PouringOrder order=fgRecord.getBean(PouringOrder.class);

		try {
			WeighOther weighOther =PublicMethod.getWeigh(order.getOrder(),1);
			if(weighOther !=null){
				PublicMethod.setPmWeightSub(order.getState(),fetchResultFactory, weighOther,order.getWeight(),PouringOrderHWANE18490Item.基本属性组_皮重,PouringOrderHWANE18490Item.基本属性组_毛重);
			}
		}catch (Exception e){
			log.info("数据处理异常:{}",JSON.toJSON(order));
		}

	}
}
